<script>
  import axios from "axios";
  import global_msg from '../../global'
  export default {
    data() {
      return {
        coverShow:false,
        coverSrc:'',
        action: '',
        // 如果在html中携带accept则默认选择规定类型的文件，否则可以在钩子函数中判断上传的文件类型
        accept: ".jpg,.png",
        // .doc,.docx,.ppt,.xls,.xlsx,.wps,.dps,.pdf,.txt,
        fileList: [],
        dialogVisible:false,
        title:'',
        content:'',
        blogType:'',
        header:'',
        blogTypes:[{
          value:'学习笔记',
          id:'1'
        },{
          value:'个人项目',
          id:'2'
        },{
          value: '技术杂烩',
          id:'3'
        },{
          value: '心情随写',
          id:'4'
        }
        ]
      };
    },
    methods: {
      handleUploadImage(event,insertImage,files) {
        // 拿到 file 之后上传到文件服务器，然后向编辑框中插入对应的内容
        for(let i in files){
          const formData = new FormData();
          formData.append('file', files[i]);
          axios.post(`upload/image`,formData).then(
            response => {
              console.log(response.data.data[0])
              insertImage({
                url:response.data.data[0],
                desc: 'DESC',
              })
            },
            error => {
              console.log('请求失败了',error.message)
            }
          )
        }
      },
      submit() {
        var formData=new FormData();
        formData.append('title',this.title);
        formData.append('content',this.content);
        formData.append('type',this.blogType);
        formData.append('header',this.header);
        formData.append('coverSrc',this.coverSrc)
        axios.post("/upload/blog",formData)
        this.$message('发布成功！')
        this.$router.push({path:'/home'})
      },
      uploadSuccess(res) { // 图片上传成功后即调用的函数
        console.log(res)
        this.coverShow = true
        this.coverSrc = global_msg.server+'/getimg/' + res.data[2]
      },
      save() {
        var formData=new FormData();
        formData.append('title',this.title);
        formData.append('content',this.content);
        formData.append('type',this.blogType);
        formData.append('header',this.header);
        formData.append('coverSrc',this.coverSrc)
        axios.post("/save/blog",formData).then(res=> {
          if(res.data.code===200) {
            this.$message('保存成功！')
          }
        })
      },
      //检查是否有之前保存的文章
      checkIsHadSave() {
        //21为保存文章的id
        axios.put('/getbyid',this.$qs.stringify({id:21})).then(res=> {
          if(res.data.data!=null||res.data.data!='') {
            this.$confirm('是否继续编辑上次保存的文章','提示',{
              confirmButtonText:'是',
              cancelButtonText:'否',
              type:'warning'
            }).then(()=> {
              this.title=res.data.data.title
              this.content=res.data.data.content
              this.blogType=res.data.data.type
              this.$forceUpdate()
            })
          }
        })
      }
    },
    mounted () {
      this.checkIsHadSave()
      this.action = 'api/upload/image'
      window.onbeforeunload = () =>{
        this.save()
        return 'tips';
      }
    }
  }
</script>

<template>
  <div>
    <el-dialog title="发布" :visible.sync="dialogVisible" width="60vw">
      <div style="margin-bottom: 10px">博客摘要：</div>
      <el-form ref="form" label-width="80px" style="width: 55vw;position: relative;left: 50%;transform: translateX(-50%)">
        <v-md-editor
          height="300px"
          @upload-image="handleUploadImage"
          v-model="header"
          :disabled-menus="[]"></v-md-editor>
        <el-upload
          class="upload-demo"
          ref="upload"
          name="file"
          :action="action"
          :on-success="uploadSuccess"
          :accept="accept"
          :limit="5"
          :show-file-list="false"
          :file-list="fileList"
          >
          <el-button size="small" type="primary" style="margin-top: 10px">上传封面</el-button>
          <div slot="tip" class="el-upload__tip" style="color:#F00"></div>
        </el-upload>
        <img v-show="coverShow" :src="coverSrc" style="width: 100%;height: 100%;position: relative;left: 50%;transform: translateX(-50%)">
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <el-input v-model="title" placeholder="请输入标题" style="width: 80%;margin-bottom: 10px">

    </el-input>
    <el-select style="width: 10%" v-model="blogType">
      <el-option v-for="item in blogTypes" :key="item.id" :label="item.value" :value="item.value"></el-option>
    </el-select>
    <el-button @click="dialogVisible = true" style="width: 8%;background: orange;color: white;margin-left: 5px">发布</el-button>
    <v-md-editor
      @save="save"
      height="1000px"
      @upload-image="handleUploadImage"
      v-model="content"
      :disabled-menus="[]"
    ></v-md-editor>
  </div>
</template>

<style>
  @import "../assets/test.css";
</style>
